<template>
  <view class="form-container">
    <uni-forms ref="form" :modelValue="formState" :rules="rules" labelPosition="top">
      <view class="hidden-title">班员状态确认</view>
      <cu-cell-group>
        <uni-forms-item name="shouldArriveNum">
          <cu-cell title="应到(人)" required>
            <input
              disabled
              type="number"
              v-model="formState.shouldArriveNum"
              placeholder="请输入"
              class="input"
              placeholder-class="form-placeholder__style"
              maxlength="10"
            />
          </cu-cell>
        </uni-forms-item>
        <uni-forms-item name="actualArriveNum">
          <cu-cell title="实到(人)" required>
            <input
              type="number"
              v-model="formState.actualArriveNum"
              placeholder="请输入"
              class="input"
              placeholder-class="form-placeholder__style"
              maxlength="10"
              @input="onInput"
            />
          </cu-cell>
        </uni-forms-item>
        <uni-forms-item name="personHealth" required>
          <cu-cell title="身体健康状态是否良好" required>
            <CuRadioGroup v-model="formState.personHealth" :list="personHealthList" />
          </cu-cell>
        </uni-forms-item>
        <uni-forms-item v-if="formState.personHealth === 1" name="unusualLog">
          <cu-cell title="异常状态记录" required column>
            <textarea v-model="formState.unusualLog" class="text-area" placeholder="请输入" maxlength="1000" />
          </cu-cell>
        </uni-forms-item>

        <uni-forms-item name="hasBothering">
          <cu-cell title="有无烦心事" required>
            <CuRadioGroup v-model="formState.hasBothering" :list="botheringList"
          /></cu-cell>
        </uni-forms-item>

        <uni-forms-item name="hasLeader">
          <cu-cell title="有无领导" required>
            <CuRadioGroup v-model="formState.hasLeader" :list="leaderHealthList" />
          </cu-cell>
        </uni-forms-item>
      </cu-cell-group>

      <cu-cell-group v-if="formState.hasLeader === 1">
        <uni-forms-item name="leaderList">
          <CuUserSelector label="到场领导" placeholder="选择领导" v-model="formState.leaderList" required multiple />
        </uni-forms-item>
      </cu-cell-group>

      <view class="title" v-if="diff > 0">
        <text>缺勤记录</text>
        <view @click="handleAddRecord" v-if="diff > formState.absentLogList.length">
          <image src="/static/images/icon-add.png" />
          <text>添加</text>
        </view>
      </view>

      <cu-cell-group v-for="(item, index) in formState.absentLogList" :key="item.key">
        <uni-forms-item
          :name="['absentLogList', index, 'userId']"
          :rules="[
            {
              required: true,
              errorMessage: '必填项不能为空'
            }
          ]"
        >
          <UserSelector
            required
            @remove="handelRemove(index)"
            :meeting-id="meetingId"
            label="人员姓名"
            :exclude-ids="excludeIds"
            placeholder="选择人员"
            v-model="formState.absentLogList[index].userId"
          />
        </uni-forms-item>
        <uni-forms-item
          :name="['absentLogList', index, 'reason']"
          :rules="[
            {
              required: true,
              errorMessage: '必填项不能为空'
            }
          ]"
        >
          <cu-cell title="缺勤原因" required column>
            <textarea
              v-model="formState.absentLogList[index].reason"
              class="text-area"
              placeholder="请输入"
              maxlength="20"
            />
          </cu-cell>
        </uni-forms-item>
      </cu-cell-group>

      <view class="background-white bor-top bottom">
        <uni-forms-item name="files" label="图片（最多三张）：" labelWidth="150">
          <image-upload state="edit" :imageUrl="formState.files" @change="imageOnChange"> </image-upload>
        </uni-forms-item>
      </view>
    </uni-forms>
    <view class="submit" @click="handleSubmit">记录</view>
  </view>
</template>

<script>
import CuUserSelector from '@/components/CuUserSelector/index.vue'
import CuCellGroup from '@/components/cu-cell/cu-cell-group.vue'
import CuCellBackNodesSelect from '@/components/CuCellBackNodesSelect/index.vue'
import ImageUpload from '@/components/image-upload/index.vue'
import CuCell from '@/components/cu-cell/cu-cell.vue'
import { recordHandle, getUserCount } from '@/api/duty-basic/duty-meeting'
import CuRadioGroup from '@/components/cu-radio-group/cu-radio-group.vue'
import UserSelector from './components/UserSelect.vue'

const absentLogListItem = { userId: '', reason: '', key: '' }

export default {
  name: '',
  data() {
    return {
      meetingNodeType: -1,
      meetingId: '',
      procTaskId: '',
      formState: {
        hasLeader: 1,
        hasBothering: 0,
        actualArriveNum: undefined,
        shouldArriveNum: undefined,
        personHealth: 0,
        leaderList: [],
        absentLogList: [],
        unusualLog: '',
        files: ''
      },
      rules: {
        hasLeader: {
          rules: [
            {
              required: true,
              errorMessage: '必填项不能为空'
            }
          ]
        },
        hasBothering: {
          rules: [
            {
              required: true,
              errorMessage: '必填项不能为空'
            }
          ]
        },
        actualArriveNum: {
          rules: [
            {
              required: true,
              errorMessage: '必填项不能为空'
            }
          ]
        },
        shouldArriveNum: {
          rules: [
            {
              required: true,
              errorMessage: '必填项不能为空'
            }
          ]
        },
        personHealth: {
          rules: [
            {
              required: true,
              errorMessage: '必填项不能为空'
            }
          ]
        },
        leaderList: {
          rules: [
            {
              required: true,
              errorMessage: '必填项不能为空'
            }
          ]
        },
        unusualLog: {
          rules: [
            {
              required: true,
              errorMessage: '必填项不能为空'
            }
          ]
        }
      },
      personHealthList: [
        {
          value: 0,
          label: '良好'
        },
        {
          value: 1,
          label: '较差'
        }
      ],
      botheringList: [
        {
          value: 0,
          label: '无'
        },
        {
          value: 1,
          label: '有'
        }
      ],
      leaderHealthList: [
        {
          value: 0,
          label: '无'
        },
        {
          value: 1,
          label: '有'
        }
      ]
    }
  },
  components: { CuRadioGroup, CuUserSelector, CuCellGroup, CuCellBackNodesSelect, ImageUpload, CuCell, UserSelector },
  methods: {
    onInput({ detail }) {
      if (detail.value < 0) this.formState.actualArriveNum = 0
      if (detail.value > this.formState.shouldArriveNum) this.formState.actualArriveNum = this.formState.shouldArriveNum
    },
    handleAddRecord() {
      if (!this.isShowAddButton) return
      this.formState.absentLogList.push({ ...absentLogListItem, key: +new Date() })
    },
    handelRemove(index) {
      this.formState.absentLogList.splice(index, 1)
    },
    async getUserCount() {
      const { data } = await getUserCount(this.meetingId)
      this.formState.shouldArriveNum = data
    },
    imageOnChange(urlList) {
      this.formState.files = urlList.join(',')
    },
    async handleSubmit() {
      await this.$refs.form.validate()
      if (this.diff > 0 && !this.formState.absentLogList?.length) {
        uni.showToast({
          icon: 'none',
          title: '实到小于应到时缺勤记录必填'
        })
        return
      }
      //入参处理
      const params = {
        procTaskId: this.procTaskId,
        meetingId: this.meetingId
      }

      this.formState.absentLogList = this.formState.absentLogList.map((item) => ({
        userId: item.userId,
        reason: item.reason,
        meetingId: this.meetingId
      }))
      uni.showModal({
        content: '提交后，填写的内容将不可以修改，请确定填写无误后再提交',
        confirmText: '确定',
        success: async (res) => {
          if (res.confirm) {
            await recordHandle({ ...this.formState, ...params })
            uni.showToast({
              title: '提交成功！',
              icon: 'success',
              duration: 2000,
              success() {
                uni.navigateBack()
              }
            })
          }
        }
      })
    }
  },
  computed: {
    diff() {
      return this.formState.shouldArriveNum - (this.formState.actualArriveNum || 0)
    },
    isShowAddButton() {
      return this.formState.absentLogList.length < this.diff
    },
    excludeIds() {
      return this.formState.absentLogList.map((item) => item.userId)
    }
  },
  watch: {
    diff(val) {
      if (val < this.formState.absentLogList.length) {
        this.formState.absentLogList = this.formState.absentLogList.slice(0, val)
      }
    }
  },
  onReady() {
    // 需要在onReady中设置规则
    this.$refs.form.setRules(this.rules)
    this.getUserCount()
  },
  onLoad({ meetingNodeType, procTaskId, id }) {
    this.meetingNodeType = meetingNodeType
    this.meetingId = id
    this.procTaskId = procTaskId
  }
}
</script>

<style lang="scss" scoped>
.title {
  display: flex;
  align-items: center;
  color: #999999;
  font-size: 26rpx;
  justify-content: space-between;
  padding: 20rpx;
  image {
    width: 48rpx;
    height: 48rpx;
    margin-right: 11rpx;
  }
  > view {
    display: flex;
    align-items: center;
  }
}
.submit {
  width: 600rpx;
  height: 88rpx;
  background: #454a5e;
  border-radius: 50rpx 50rpx 50rpx 50rpx;
  opacity: 1;
  text-align: center;
  line-height: 88rpx;
  font-size: 36rpx;
  font-weight: 400;
  color: #ffffff;
  margin: 0 auto;
  margin-top: 70rpx;
  margin-bottom: 70rpx;
}

.margin-0 {
  margin-bottom: 0;
  position: relative;
  &::after {
    content: '';
    height: 0.5rpx;
    background: #d5d7e3;
    position: absolute;
    right: 0;
    left: 30rpx;
    bottom: 0;
  }
}
::v-deep .cu-radio-group {
  height: 100%;
  align-items: center;
  justify-content: flex-end;
  > .cu-radio-item {
    padding-right: 0;
    margin-left: 60rpx;
  }
}
</style>
